package com.fengxing.ams.web.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginFilter extends org.apache.shiro.web.filter.authc.UserFilter {
    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);
    private static final String INDEX_URI = "/";
    private static final String LOGIN_URI = "/login.html";
    private static final String LOGININDEX_URI = "/index.html#ajax/bfjh.html";
    
    private static final String SYSLOGIN_URI = "/syslogin.html";
    private static final String SYSINDEX_URI = "/sysindex.html#ajax/friendquery.html";
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		String requestURI = getPathWithinApplication(request);
		
    	if(pathsMatch(INDEX_URI, requestURI)) {
    		WebUtils.issueRedirect(request, response, LOGININDEX_URI);
    	}
    	
    	if(pathsMatch(LOGIN_URI, requestURI)) {
    		WebUtils.issueRedirect(request, response, LOGININDEX_URI);
    	}
    	
    	if(pathsMatch(SYSLOGIN_URI, requestURI)) {
    		WebUtils.issueRedirect(request, response, SYSINDEX_URI);
    	}
        return false;
    }
    
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		String requestURI = getPathWithinApplication(request);
        Subject subject = getSubject(request, response);
        if(subject.getPrincipal() != null) {
        	if(pathsMatch(INDEX_URI, requestURI)) {
        		return false;
        	}
        	
        	if(pathsMatch(LOGIN_URI, requestURI)) {
        		return false;
        	}
        	
        	if(pathsMatch(SYSLOGIN_URI, requestURI)) {
        		return false;
        	}
        }
        return true;
	}
}
